package com.zhuzi.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author zhuzi
 */
public class MyIdGenerator implements IdentifierGenerator {
    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {

        Serializable id = session.getEntityPersister(null, obj).getClassMetadata().getIdentifier(obj, session);

        if (Objects.isNull(id)) {
            //https://www.cnblogs.com/relucent/p/4955340.html
            Snowflake snowflake = IdUtil.getSnowflake(1, 1);
            return snowflake.nextId();
        } else {
            return id;
        }
    }
}
